﻿using IdentityService.Domain.Aggregates.PermitAggregate;
using IdentityService.Domain.Repositories;
using Microsoft.EntityFrameworkCore;

namespace IdentityService.Infrastructure.EFRepositories
{
    public class EFPermitRepository : IPermitRepository
    {
        private readonly AppIdentityDbContext _context;
        public EFPermitRepository(AppIdentityDbContext context) => _context = context;

        public async Task AddAsync(Permit permit)
        {
            await _context.Permit.AddAsync(permit);
        }

        public void Delete(Permit permit)
        {
            _context.Permit.Remove(permit);
        }

        public void DeleteRangeAndSave(List<Permit> list)
        {
            _context.Permit.RemoveRange(list);
            _context.SaveChanges();
        }

        public async Task<Permit?> FindByIdAsync(long id)
        {
            return await _context.Permit.FirstOrDefaultAsync(it => it.Id == id);
        }

        public async Task<Permit?> FindByIdWithChildrenAsync(long id)
        {
            return await _context.Permit.Include(it => it.Children).FirstOrDefaultAsync(it => it.Id == id);
        }

        public async Task<List<Permit>> FindSolitaryRecords()
        {
            return await _context.Permit.Include(it => it.Children).Where(it => it.ParentId == null).ToListAsync();
        }

        public async Task<bool> CheckExistByIdAsync(long id)
        {
            return await _context.Permit.AnyAsync(it => it.Id == id);
        }

        public async Task<bool> CheckExistByNameAsync(string name)
        {
            return await _context.Permit.AnyAsync(it => it.Name == name);
        }
    }
}
